@workover/mcp 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @workover/mcp
2
2
 
3
- An [MCP](https://modelcontextprotocol.io) server for [Workover](https://workover.dev) — lets Claude Code (and other MCP clients) read your Workover documents and propose edits you review.
3
+ An [MCP](https://modelcontextprotocol.io) server for [Workover](https://workover.dev) — lets Claude Code (and other MCP clients) read your Workover documents, create new ones, and propose edits you review.
4
4
 
5
5
  ## Setup
6
6
 
@@ -24,16 +24,53 @@ That's it. Ask Claude Code things like *"read my Workover doc about onboarding a
24
24
  - `workover_search_docs(query)` — find documents by title/content
25
25
  - `workover_read_doc(docId)` — read a document's text
26
26
  - `workover_list_projects()` — list your projects
27
+ - `workover_create_doc(projectId, title, markdown)` — create a document with its content written in
28
+ - `workover_upload_image(docId, path, alt)` — put a local image into a document's media
27
29
  - `workover_propose_edit(docId, markdown, note)` — propose a revised version (rendered as suggestions; never applied or published automatically)
30
+ - `workover_edit_doc(docId, markdown, note)` — edit a document directly, no review step. Needs `workover login --write`
31
+
32
+ Everything the MCP server can do, the CLI can do too (`workover doc create|read|propose|write|list|search`). That is deliberate: a newly-registered MCP server is not available in the session that registered it, so an agent that finds mid-task that it needs Workover has no way in until it restarts. A CLI subcommand works immediately.
28
33
 
29
34
  ## Safety
30
35
 
31
- The server authenticates with the token from `workover login` and is **read + propose only**. It cannot publish to WordPress, change your account, or apply changes without you. Every edit is a suggestion a human accepts, and only a human publishes. Revoke access anytime in **Workover → Settings → Developer**.
36
+ The server authenticates with the token from `workover login`. By default it is **read + propose only**: it cannot publish to WordPress, change your account, or apply changes without you. Every edit is a suggestion you accept, and only a person publishes. Revoke access anytime in **Workover → Settings → Developer**.
37
+
38
+ Two deliberate exceptions, both of which still stop short of publishing:
39
+
40
+ - **A new document's first content is written in, not proposed.** `workover_create_doc` creates the document and its body together. A document that did not exist a second ago has no text to protect, and asking you to accept your own content against an empty page is a review step with nothing in it.
41
+ - **`workover_edit_doc` edits an existing document directly** — for when you are working alongside the agent and say "make that change", rather than getting fifty tracked suggestions to click through for an edit you just asked for. It only works if you granted it: sign in with `workover login --write`, and the browser tells you exactly that before you approve. Without it the tool returns a permission error and proposing is the way through.
32
42
 
33
43
  ## Configuration
34
44
 
35
45
  The API endpoint comes from your `workover login` (defaults to `https://api.workover.dev`).
36
46
 
47
+ ## Usage data
48
+
49
+ To learn which tools agents actually reach for and where they fail, this server records **one event
50
+ per tool call**:
51
+
52
+ - the tool name (`workover_read_doc`, `workover_search_docs`, ...)
53
+ - how long the call took, and whether it succeeded
54
+ - which MCP client called it (Claude Code, Cursor, ...) and its version
55
+
56
+ **It never sends your documents.** Not the arguments you pass, not the results you get back, not
57
+ your file paths. `workover_propose_edits` takes an entire document as an argument and that argument
58
+ is never read by this. What is sent is the shape of the call, not its contents.
59
+
60
+ It is sent **to Workover's own API**, using the token you already signed in with, and is recorded
61
+ against your Workover account. The server ships no analytics credential of its own and talks to no
62
+ third party directly.
63
+
64
+ Turn it off with either of:
65
+
66
+ ```bash
67
+ export DO_NOT_TRACK=1 # the cross-tool standard; disables it here too
68
+ export WORKOVER_TELEMETRY=0 # this package only
69
+ ```
70
+
71
+ Nothing is sent when you are not signed in, and nothing is sent from a local development setup or
72
+ from any API host other than Workover's own.
73
+
37
74
  ---
38
75
 
39
76
  © ScaleMath. All rights reserved.
package/index.mjs CHANGED
@@ -13,6 +13,11 @@ import { readFileSync } from 'fs';
13
13
  import { homedir } from 'os';
14
14
  import { join } from 'path';
15
15
  import { makeApi, makeDispatch, validAuth } from './lib.mjs';
16
+ import {
17
+ buildToolCallEvent,
18
+ sendEvent,
19
+ telemetryEnabled,
20
+ } from './telemetry.mjs';
16
21
 
17
22
  function loadAuth() {
18
23
  try {
@@ -59,7 +64,7 @@ const TOOLS = [
59
64
  {
60
65
  name: 'workover_create_doc',
61
66
  description:
62
- "Create a new document in a Workover project (find the projectId with workover_list_projects). The body is added as a proposal, so it appears as tracked-change suggestions for the person to review and accept when they open the doc — nothing is published. Returns the new document's id and URL.",
67
+ "Create a new document in a Workover project (find the projectId with workover_list_projects), with its content written straight in — a brand-new document has no prior text, so there is nothing to review the first body against. Later changes to it go through workover_propose_edit as suggestions. Nothing is published to WordPress. Returns the new document's id and URL.",
63
68
  inputSchema: {
64
69
  type: 'object',
65
70
  properties: {
@@ -91,6 +96,30 @@ const TOOLS = [
91
96
  required: ['docId', 'path'],
92
97
  },
93
98
  },
99
+ {
100
+ name: 'workover_edit_doc',
101
+ description:
102
+ "Edit a Workover document DIRECTLY, replacing its body with no suggestions for anyone to review. Use this ONLY when the person has asked for the change to be made — working together on a document they have open, 'just make that edit'. Otherwise use workover_propose_edit, which is the default and leaves them something to accept or reject. Read the document first (workover_read_doc) and provide the FULL revised document: this REPLACES the body, so anything omitted is deleted. Requires a token from `workover login --write`; without that scope this returns a permission error and proposing is the way through. Never publishes to WordPress.",
103
+ inputSchema: {
104
+ type: 'object',
105
+ properties: {
106
+ docId: {
107
+ type: 'number',
108
+ description: 'The numeric id of the document to edit (not a URL handle).',
109
+ },
110
+ markdown: {
111
+ type: 'string',
112
+ description:
113
+ 'The complete document as markdown. It replaces the current body in full — anything left out is removed.',
114
+ },
115
+ note: {
116
+ type: 'string',
117
+ description: 'A short summary of what you changed, kept in the audit log.',
118
+ },
119
+ },
120
+ required: ['docId', 'markdown'],
121
+ },
122
+ },
94
123
  {
95
124
  name: 'workover_propose_edit',
96
125
  description:
@@ -117,6 +146,12 @@ const TOOLS = [
117
146
  },
118
147
  ];
119
148
 
149
+ const telemetry = telemetryEnabled(process.env, { auth });
150
+ // Keep in step with package.json. It is what every telemetry event is stamped with, so a stale
151
+ // value here does not break anything — it quietly attributes this release's behaviour to an older
152
+ // one, which is worse, because the numbers still look fine.
153
+ const VERSION = '0.4.0';
154
+
120
155
  const server = new Server(
121
156
  { name: 'workover', version: '0.1.0' },
122
157
  { capabilities: { tools: {} } },
@@ -124,9 +159,52 @@ const server = new Server(
124
159
 
125
160
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
126
161
 
162
+ /**
163
+ * Which tools agents reach for, and where they fail.
164
+ *
165
+ * Wrapped HERE because every tool call arrives through this one handler, so instrumenting it cannot
166
+ * miss a tool the way per-tool instrumentation would as soon as somebody adds the next one.
167
+ *
168
+ * `args` is in scope and is deliberately never touched. For this server the arguments ARE the
169
+ * customer's documents - `workover_propose_edits` takes the complete revised document - so the
170
+ * event carries the tool NAME, how long it took and whether it worked, and nothing else. See
171
+ * telemetry.mjs.
172
+ *
173
+ * The result is returned before the event is sent, and the send is never awaited: an MCP server
174
+ * that made an agent wait on an analytics endpoint would be a worse product than one with no
175
+ * analytics at all.
176
+ */
127
177
  server.setRequestHandler(CallToolRequestSchema, async (req) => {
128
178
  const { name, arguments: args = {} } = req.params;
129
- return dispatch(name, args);
179
+ if (!telemetry) return dispatch(name, args);
180
+
181
+ const startedAt = Date.now();
182
+ try {
183
+ const result = await dispatch(name, args);
184
+ report(name, startedAt, !result?.isError, result?.isError ? 'tool_error' : null);
185
+ return result;
186
+ } catch (error) {
187
+ // Reported, then rethrown untouched. A crash in our dispatch must still reach the client as a
188
+ // crash; swallowing it to keep the analytics tidy would hide the bug.
189
+ report(name, startedAt, false, 'exception');
190
+ throw error;
191
+ }
130
192
  });
131
193
 
194
+ function report(tool, startedAt, ok, errorKind) {
195
+ void sendEvent(
196
+ buildToolCallEvent({
197
+ tool,
198
+ durationMs: Date.now() - startedAt,
199
+ ok,
200
+ errorKind,
201
+ version: VERSION,
202
+ client: server.getClientVersion?.() ?? null,
203
+ }),
204
+ // The API attributes the event to whoever this token belongs to. Nothing here nominates an
205
+ // identity, because a client that could would be a client that could claim somebody else's.
206
+ { auth },
207
+ );
208
+ }
209
+
132
210
  await server.connect(new StdioServerTransport());
package/lib.mjs CHANGED
@@ -16,8 +16,53 @@ export const text = (t) => ({ content: [{ type: 'text', text: t }] });
16
16
  /** Wrap a string as an MCP tool error result (isError: true → the client shows it as a failure). */
17
17
  export const err = (t) => ({ content: [{ type: 'text', text: t }], isError: true });
18
18
 
19
- /** True only when a stored config has both a token and an api base — the sign-in gate. */
20
- export const validAuth = (cfg) => (cfg?.token && cfg?.api ? cfg : null);
19
+ /**
20
+ * Whether a stored config is usable — the sign-in gate.
21
+ *
22
+ * Both a token and an api base, and THE BASE MUST BE HTTPS. That last part is a real constraint
23
+ * rather than tidiness: every request this server makes sends the bearer token to whatever host the
24
+ * config file names, so the file is an exfiltration primitive for anything that can write it. It is
25
+ * a modest one — anything able to write that file can already read the token out of it — but
26
+ * sending the credential in clear text to an arbitrary host is a step worse than merely having it
27
+ * stolen locally, and it costs nothing to refuse.
28
+ *
29
+ * This does NOT satisfy CodeQL's `js/file-access-to-http`, and it was written believing it would.
30
+ * Validating a value and then still using it leaves the dataflow exactly as it was - file to
31
+ * network - so the alert stayed open, correctly. Telemetry resolves its address from a fixed table
32
+ * instead (see `telemetry.mjs`), which it can afford to do because it is optional. A tool call
33
+ * cannot: it MUST reach whatever API the user signed in to, so here the honest answer is a
34
+ * constraint on the value rather than a replacement of it.
35
+ *
36
+ * Which is worth keeping regardless of what any checker thinks of it: the token travels to
37
+ * whatever host this file names, and clear text to an arbitrary host is a step worse than a
38
+ * credential stolen locally.
39
+ *
40
+ * `http://localhost` and `127.0.0.1` are allowed, because local development is the one case where
41
+ * there is no network to sniff and requiring a certificate would just make people turn the check
42
+ * off.
43
+ */
44
+ export const validAuth = (cfg) => {
45
+ if (!cfg?.token || !cfg?.api) return null;
46
+ return isSafeApiBase(cfg.api) ? cfg : null;
47
+ };
48
+
49
+ /** An https origin, or a loopback address during local development. */
50
+ export const isSafeApiBase = (api) => {
51
+ let url;
52
+ try {
53
+ url = new URL(String(api));
54
+ } catch {
55
+ return false;
56
+ }
57
+ if (url.protocol === 'https:') return true;
58
+ return (
59
+ url.protocol === 'http:' &&
60
+ (url.hostname === 'localhost' ||
61
+ url.hostname === '127.0.0.1' ||
62
+ url.hostname === '[::1]' ||
63
+ url.hostname === '::1')
64
+ );
65
+ };
21
66
 
22
67
  /**
23
68
  * Coerce a tool-supplied row id, or null if it isn't one.
@@ -41,6 +86,19 @@ export const badIdErr = (kind, got) =>
41
86
  `"${got}" isn't a ${kind} id. Pass the numeric id (e.g. 12345) — the one workover_search_docs prints as "#12345" or workover_list_projects as "#7". A handle from a document URL won't work here.`,
42
87
  );
43
88
 
89
+ /**
90
+ * Whether a just-created document came back with its body already in it.
91
+ *
92
+ * The create call sends `markdown`, and a Workover that understands it writes the content directly
93
+ * — there is no prior text on a document one call old, so there is nothing for a human to accept or
94
+ * reject. An older API validates the body with a whitelist and silently DROPS the field, returning
95
+ * a perfectly successful empty document. That is the failure worth catching: the content would be
96
+ * gone with nothing said. So the answer is read off the response rather than assumed, and the
97
+ * caller falls back to proposing when it is no.
98
+ */
99
+ export const contentCommitted = (doc) =>
100
+ typeof doc?.content === 'string' && doc.content.trim().length > 0;
101
+
44
102
  /** Map an image file extension to its mime type (defaults to png). */
45
103
  export const mimeForExt = (ext) => {
46
104
  const e = String(ext || '').toLowerCase();
@@ -61,7 +119,16 @@ export function makeApi({ auth, fetchImpl = fetch }) {
61
119
  });
62
120
  if (res.status === 401)
63
121
  throw new Error('Your Workover login expired or was revoked. Run `workover login`.');
64
- if (res.status === 403) throw new Error('This token isn’t allowed to do that.');
122
+ if (res.status === 403) {
123
+ // The API's own sentence when it sent one. A scope refusal names the scope and the command
124
+ // that grants it ("Re-run `workover login --write`"), which is the difference between an
125
+ // agent that can fix this and one that reports a flat "not allowed" and stops.
126
+ const detail = await res
127
+ .json()
128
+ .then((body) => (typeof body?.message === 'string' ? body.message : ''))
129
+ .catch(() => '');
130
+ throw new Error(detail || 'This token isn’t allowed to do that.');
131
+ }
65
132
  if (!res.ok) throw new Error(`Workover API error (${res.status}).`);
66
133
  return res.json();
67
134
  }
@@ -118,14 +185,28 @@ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }
118
185
  if (!title || !md) return err('Provide both a `title` and the body as `markdown`.');
119
186
  const projectId = rowId(args.projectId);
120
187
  if (projectId === null) return badIdErr('project', args.projectId);
121
- const doc = await apiPost(`/project/${projectId}/documents`, { title });
188
+ // The body goes WITH the create. A document this call brought into existence has no prior
189
+ // text to protect, so its first content is written directly rather than queued as
190
+ // suggestions for the person to accept against an empty page.
191
+ const doc = await apiPost(`/project/${projectId}/documents`, {
192
+ title,
193
+ markdown: md,
194
+ });
122
195
  if (!doc?.id) return err('Could not create the document.');
196
+ if (contentCommitted(doc)) {
197
+ return text(
198
+ `Created "${title}" (document #${doc.id}) with the content written in — no review step, because it is a new document.${doc.documentUrl ? `\n${doc.documentUrl}` : ''}\n\nFurther changes to it go through workover_propose_edit, which the person accepts or rejects. Nothing is published to WordPress either way.`,
199
+ );
200
+ }
201
+ // This Workover predates create-with-content and dropped the field, leaving an empty
202
+ // document. Propose the body instead of losing it, and say which of the two happened —
203
+ // "created" over an empty page reads like success right up until somebody opens it.
123
204
  const proposal = await apiPost(`/project/doc/${doc.id}/propose`, {
124
205
  markdown: md,
125
206
  source: 'Claude Code',
126
207
  });
127
208
  return text(
128
- `Created "${title}" (document #${doc.id}) and added the content as suggestions to review.${proposal?.documentUrl ? `\n${proposal.documentUrl}` : ''}\n\nOpen it in Workover to accept or reject the changes — nothing is published.`,
209
+ `Created "${title}" (document #${doc.id}). This Workover can't write a new document's content directly, so the body is waiting as suggestions instead.${proposal?.documentUrl ? `\n${proposal.documentUrl}` : ''}\n\nOpen it in Workover and accept them — the document is empty until you do.`,
129
210
  );
130
211
  }
131
212
  if (name === 'workover_upload_image') {
@@ -155,6 +236,24 @@ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }
155
236
  `Uploaded. Reference it in the document markdown:\n\n![${args.alt || 'screenshot'}](${url})`,
156
237
  );
157
238
  }
239
+ if (name === 'workover_edit_doc') {
240
+ const md = String(args.markdown || '').trim();
241
+ if (!md) return err('Provide the full revised document as `markdown`.');
242
+ const docId = rowId(args.docId);
243
+ if (docId === null) return badIdErr('document', args.docId);
244
+ const res = await apiPost(`/project/doc/${docId}/content`, {
245
+ markdown: md,
246
+ note: args.note ? String(args.note) : undefined,
247
+ source: 'Claude Code',
248
+ });
249
+ return text(
250
+ `Edited document #${docId} directly — the new text is in the document and there is nothing to accept.${res?.documentUrl ? `\n${res.documentUrl}` : ''}${
251
+ res?.replacedCharacters
252
+ ? `\n\nReplaced ${res.replacedCharacters} characters of existing text.`
253
+ : ''
254
+ }`,
255
+ );
256
+ }
158
257
  if (name === 'workover_propose_edit') {
159
258
  const md = String(args.markdown || '').trim();
160
259
  if (!md) return err('Provide the full revised document as `markdown`.');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workover/mcp",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Workover MCP server — let Claude Code and other MCP clients read and cowork on your Workover documents.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "ScaleMath",
@@ -22,6 +22,7 @@
22
22
  "files": [
23
23
  "index.mjs",
24
24
  "lib.mjs",
25
+ "telemetry.mjs",
25
26
  "README.md"
26
27
  ],
27
28
  "engines": {
package/telemetry.mjs ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Which tools agents actually reach for, and where they fail.
3
+ *
4
+ * This is the question worth answering about an MCP server: we ship tools into other people's
5
+ * agents and have no idea which ones get used, which get called with bad arguments, or which are
6
+ * slow enough that an agent gives up.
7
+ *
8
+ * WHAT IT NEVER SENDS, AND WHY THAT IS NOT NEGOTIABLE
9
+ *
10
+ * Not the arguments. Not the results. PostHog's MCP analytics describes capturing "every tool call,
11
+ * argument and result", and for THIS server that would mean shipping customers' documents off their
12
+ * own laptops: `workover_propose_edits` takes the complete revised document as an argument, and
13
+ * every read tool returns document contents. Nobody installing an MCP server expects it to send
14
+ * their writing to the vendor's analytics, and "we captured the arguments" is not a defence.
15
+ *
16
+ * So: the tool NAME, how long it took, whether it worked, and what kind of failure it was.
17
+ *
18
+ * IT REPORTS THROUGH THE WORKOVER API, NOT STRAIGHT TO POSTHOG
19
+ *
20
+ * The first version embedded a PostHog project token in the published package. The reasoning was
21
+ * that these tokens are write-only and documented as safe in public clients, which is true - it is
22
+ * the same token a web app exposes in its bundle. It was still the wrong call for two reasons that
23
+ * have nothing to do with how dangerous the token is:
24
+ *
25
+ * A credential in a published tarball is a credential you cannot rotate. Changing it means every
26
+ * installed copy keeps using the old one until each user upgrades, so the thing that makes
27
+ * rotation possible - being able to stop honouring the old value - is exactly what you lose. It
28
+ * also trips secret scanning on every push, and an alert that is always there is an alert nobody
29
+ * reads.
30
+ *
31
+ * It threw away the identity. A hash of the token is a pseudonym: it groups one installation's
32
+ * calls together and tells you nothing else. Sent through the API, the server already knows who
33
+ * the token belongs to, so MCP usage lands on the same person and workspace as everything else -
34
+ * which is what makes "this workspace uses the MCP server heavily and drafts nothing" a question
35
+ * anyone can ask.
36
+ *
37
+ * The cost, stated rather than discovered: an unauthenticated install now reports NOTHING, because
38
+ * there is no token to authenticate the relay with and no API base configured to send it to. That
39
+ * loses the "somebody installed it and never signed in" signal. It is a thin signal - an
40
+ * unauthenticated server cannot complete a single tool call anyway, since every tool goes through
41
+ * the API - and the alternative was a public unauthenticated write endpoint into our own analytics,
42
+ * which is the same junk-event exposure as the embedded token with none of the benefit.
43
+ *
44
+ * WHERE IT MAY SEND, AND WHY THAT IS A FIXED LIST
45
+ *
46
+ * Only to a host in `KNOWN_API_BASES`, and the URL is taken FROM that table rather than from the
47
+ * config file - the file's host is only ever used as a lookup key. So the address this posts to is
48
+ * a constant in this source file, and nothing a config file says can change it.
49
+ *
50
+ * That is stricter than the tool calls in `lib.mjs`, deliberately. A tool call must reach whatever
51
+ * API the user signed in to or the product does not work; telemetry is optional, so it can afford
52
+ * to refuse anything it does not already recognise. Local development therefore reports nothing,
53
+ * which is also what we want - it keeps our own machines out of "which clients use which tools".
54
+ *
55
+ * CodeQL found the previous version as `js/file-access-to-http`. The first attempt at a fix only
56
+ * validated the file's value (https, or loopback) and still built the URL from it, which hardened
57
+ * the behaviour without changing the dataflow at all - the alert stayed open, correctly.
58
+ *
59
+ * IT RUNS ON SOMEONE ELSE'S MACHINE
60
+ *
61
+ * Unlike the API, this is a published npm package executing on a customer's laptop. Telemetry that
62
+ * is on by default without disclosure is a thing done TO people, so: `DO_NOT_TRACK` is honoured
63
+ * (the cross-tool standard), `WORKOVER_TELEMETRY=0` turns it off explicitly, and the README says
64
+ * what is collected before anyone installs it.
65
+ */
66
+
67
+ export const TOOL_CALL_EVENT = 'mcp_tool_call';
68
+
69
+ /**
70
+ * Every host telemetry may be sent to, and the exact base URL used for each.
71
+ *
72
+ * The VALUE is what gets used, never the key and never the config file's own string. A host we do
73
+ * not recognise - a fork, a self-hosted API, localhost - reports nothing rather than being trusted
74
+ * with a bearer token.
75
+ */
76
+ const KNOWN_API_BASES = {
77
+ 'api.workover.io': 'https://api.workover.io',
78
+ 'api.workover.dev': 'https://api.workover.dev',
79
+ };
80
+
81
+ /**
82
+ * The base URL to report to, or null for "do not report".
83
+ *
84
+ * Returns a constant from the table above. The configured value is parsed only to read its
85
+ * hostname, which is used as a lookup key and then discarded.
86
+ */
87
+ export function telemetryBaseFor(api) {
88
+ let hostname;
89
+ try {
90
+ hostname = new URL(String(api)).hostname;
91
+ } catch {
92
+ return null;
93
+ }
94
+ return Object.prototype.hasOwnProperty.call(KNOWN_API_BASES, hostname)
95
+ ? KNOWN_API_BASES[hostname]
96
+ : null;
97
+ }
98
+
99
+ /**
100
+ * Whether to send anything at all.
101
+ *
102
+ * Opt-OUT rather than opt-in, which is the choice worth being honest about: opt-in telemetry from a
103
+ * CLI is telemetry nobody enables, so the data would not exist. That is only defensible because
104
+ * what is sent carries no content, and because turning it off is one standard environment variable
105
+ * that many people already set globally.
106
+ *
107
+ * Signed in is now a precondition rather than a property of the event. There is nowhere to send an
108
+ * anonymous one: the API base lives in the same stored config as the token.
109
+ */
110
+ export function telemetryEnabled(env = process.env, { auth = null } = {}) {
111
+ if (env.DO_NOT_TRACK === '1' || env.DO_NOT_TRACK === 'true') return false;
112
+ if (env.WORKOVER_TELEMETRY === '0' || env.WORKOVER_TELEMETRY === 'false') {
113
+ return false;
114
+ }
115
+ return Boolean(auth?.token && telemetryBaseFor(auth?.api));
116
+ }
117
+
118
+ /**
119
+ * One tool call, as an event.
120
+ *
121
+ * `ok` is separate from `errorKind` on purpose: a tool that returned `isError` is a DIFFERENT thing
122
+ * from a tool that threw, and collapsing them would hide the case where our own dispatch crashes
123
+ * behind the ordinary "no documents matched" answer.
124
+ *
125
+ * No `distinct_id`. The API knows whose token this is and attributes it there - a client that
126
+ * nominated its own identity could claim anybody's, and the server would have no way to tell.
127
+ */
128
+ export function buildToolCallEvent({
129
+ tool,
130
+ durationMs,
131
+ ok,
132
+ errorKind = null,
133
+ version = null,
134
+ client = null,
135
+ }) {
136
+ return {
137
+ event: TOOL_CALL_EVENT,
138
+ properties: {
139
+ mcp_tool: tool,
140
+ mcp_duration_ms: Math.max(0, Math.round(durationMs)),
141
+ mcp_ok: Boolean(ok),
142
+ ...(errorKind ? { mcp_error_kind: errorKind } : {}),
143
+ ...(version ? { mcp_server_version: version } : {}),
144
+ // Which agent is calling: Claude Code, Cursor, Codex. The whole point of the question is
145
+ // which clients use which tools, and the MCP handshake tells us without asking the user.
146
+ ...(client?.name ? { mcp_client: client.name } : {}),
147
+ ...(client?.version ? { mcp_client_version: client.version } : {}),
148
+ },
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Send one event, and never let it matter.
154
+ *
155
+ * Fire-and-forget with a short timeout, every failure swallowed. An MCP server that stalls or
156
+ * crashes because an analytics endpoint is slow would be a straightforwardly worse product than one
157
+ * with no analytics at all - and this one runs on somebody's laptop while they are trying to work.
158
+ *
159
+ * Nothing is ever written to stdout. This process speaks the MCP protocol over stdio, so a stray
160
+ * `console.log` corrupts the stream and breaks the client - which is a much easier mistake to make
161
+ * than it looks.
162
+ */
163
+ export async function sendEvent(event, { auth, fetchImpl } = {}) {
164
+ // The base comes from the table, not from the file. Re-resolved here rather than trusted from
165
+ // the caller: a guard that only exists somewhere else is a guard the next caller will not have.
166
+ const base = auth?.token ? telemetryBaseFor(auth.api) : null;
167
+ if (!base) return false;
168
+
169
+ const doFetch = fetchImpl ?? globalThis.fetch;
170
+ if (typeof doFetch !== 'function') return false;
171
+
172
+ const controller = new AbortController();
173
+ const timer = setTimeout(() => controller.abort(), 2000);
174
+
175
+ try {
176
+ await doFetch(`${base}/mcp/telemetry`, {
177
+ method: 'POST',
178
+ headers: {
179
+ 'content-type': 'application/json',
180
+ authorization: `Bearer ${auth.token}`,
181
+ },
182
+ body: JSON.stringify({
183
+ event: event.event,
184
+ properties: event.properties,
185
+ }),
186
+ signal: controller.signal,
187
+ });
188
+ return true;
189
+ } catch {
190
+ return false;
191
+ } finally {
192
+ clearTimeout(timer);
193
+ }
194
+ }